package ru.sviridov.sellandbuy.url;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;

import org.apache.http.protocol.HTTP;

import android.util.Log;

// help - https://api.istsoft.ru/
// api.istsoft.ru/1.0/Membership.asmx/Register
// {"token":"F7DD9CC0-8663-4436-ACEB-07A03ED1D98C", "login":"admin", "passwordMd5":"wathelle!1"}
//Content-Type: application/json; charset=utf-8

public class ServiceClient {
	private static final int CONNECTION_TIMEOUT = 10000;
	private static final int SOCKET_TIMEOUT = 10000;
	private static final String METHOD = "POST";
	private static final String CONTENT_TYPE = "application/json";
	
	private int errorCode=HttpURLConnection.HTTP_BAD_REQUEST;
	private String response;
	
	public ServiceClient(){
	}
	
	/** @return error code*/
	public int query(String urlString, String jsonParams) {
		Log.i("SERVICE", "REQUEST: " + urlString);
		Log.i("SERVICE", "REQUEST BODY:"+jsonParams);
		
		response = communicate(urlString, jsonParams);
		
		Log.i("SERVICE", "RESPONSE:"+response);
		
		return errorCode;
	}
	
	public int getErrorCode(){
		return errorCode;
	}

	public String getResponse(){
		return response;
	}

	/** return response content or null*/
	private String communicate(String urlString, String requestBody) { 
		StringBuilder sBuilder = new StringBuilder();
		HttpsURLConnection urlConnection = null;
		BufferedReader bReader = null;
		try {
			urlConnection = (HttpsURLConnection) new URL(urlString).openConnection();
//			urlConnection.setHostnameVerifier(v);
			configConnection(urlConnection, requestBody.length());
			attachBody(urlConnection,requestBody);
			errorCode = urlConnection.getResponseCode();
			bReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), HTTP.UTF_8));

			String line; // TODO optimize reading using nio or byte reading
			while ((line = bReader.readLine()) != null) {
				sBuilder.append(line);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (bReader != null)
				try { bReader.close(); } catch (IOException e) { e.printStackTrace(); }
			if (urlConnection != null)
				urlConnection.disconnect();
		}

		return sBuilder.toString();
	}
	
	private void attachBody(HttpURLConnection urlConnection, String requestBody) throws IOException {
		BufferedWriter out = new BufferedWriter(new OutputStreamWriter(urlConnection.getOutputStream()));
		out.write(requestBody);
		out.flush();
		out.close();		
	}

	private void configConnection(HttpURLConnection urlConnection, int length) throws ProtocolException {
		urlConnection.setDoOutput(true); //setting request type "POST"
		urlConnection.setRequestMethod(METHOD);
		urlConnection.setDoInput(true);
//		urlConnection.setFixedLengthStreamingMode(length);
		urlConnection.setConnectTimeout(CONNECTION_TIMEOUT);
		urlConnection.setReadTimeout(SOCKET_TIMEOUT);
		urlConnection.setRequestProperty("Content-Language", "ru-RU");
		urlConnection.setRequestProperty("Accept-Charset", HTTP.UTF_8);
		urlConnection.setRequestProperty("Accept-Encoding", HTTP.IDENTITY_CODING);
		urlConnection.setRequestProperty(HTTP.CONTENT_TYPE, CONTENT_TYPE);
	}

}
